<template>
  <div class="separate-view">
    <h2>音视频分离</h2>
    <div class="card">
      <div class="upload-area" @click="selectFile">
        <p v-if="!inputFile">点击选择视频文件</p>
        <p v-else>{{ inputFile }}</p>
      </div>

      <div v-if="inputFile" class="options">
        <div class="option-group">
          <label>提取类型</label>
          <select v-model="extractType">
            <option value="audio">仅提取音频</option>
            <option value="video">仅提取视频</option>
            <option value="both">同时提取</option>
          </select>
        </div>

        <div v-if="extractType === 'audio' || extractType === 'both'" class="option-group">
          <label>音频格式</label>
          <select v-model="audioFormat">
            <option value="mp3">MP3</option>
            <option value="aac">AAC</option>
            <option value="wav">WAV</option>
            <option value="flac">FLAC</option>
          </select>
        </div>

        <button @click="separate" :disabled="processing" class="btn-primary">
          {{ processing ? '处理中...' : '开始提取' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const inputFile = ref('');
const extractType = ref('audio');
const audioFormat = ref('mp3');
const processing = ref(false);

const selectFile = async () => {
  const result = await window.electronAPI.dialog.openFile({
    filters: [{ name: 'Videos', extensions: ['mp4', 'avi', 'mov', 'mkv', 'webm'] }],
  });

  if (!result.canceled && result.filePaths[0]) {
    inputFile.value = result.filePaths[0];
  }
};

const separate = async () => {
  processing.value = true;

  try {
    const options: any = {
      input: inputFile.value,
      extractType: extractType.value,
    };

    if (extractType.value === 'audio' || extractType.value === 'both') {
      const audioResult = await window.electronAPI.dialog.saveFile({
        defaultPath: `audio.${audioFormat.value}`,
        filters: [{ name: 'Audio', extensions: [audioFormat.value] }],
      });
      if (audioResult.canceled) {
        processing.value = false;
        return;
      }
      options.audioOutput = audioResult.filePath;
      options.audioFormat = audioFormat.value;
    }

    if (extractType.value === 'video' || extractType.value === 'both') {
      const videoResult = await window.electronAPI.dialog.saveFile({
        defaultPath: 'video.mp4',
        filters: [{ name: 'Video', extensions: ['mp4'] }],
      });
      if (videoResult.canceled) {
        processing.value = false;
        return;
      }
      options.videoOutput = videoResult.filePath;
    }

    await window.electronAPI.video.separate(options);
    alert('提取完成！');
  } catch (error) {
    alert('提取失败：' + error);
  } finally {
    processing.value = false;
  }
};
</script>

<style scoped>
@import '../styles/ConvertView.scss';
</style>
